<template>
  <Layout>

    <div>
      <el-card>
        <el-row type="flex" justify="space-between">
          <el-form ref="input3" v-model="input3" size="small" class="demo-form-inline" inline>



            <el-form-item>
              <el-input v-model="input3" placeholder="请输入证书编号或证书名字" />

            </el-form-item>
            <el-button v-model="input3" type="primary" icon="el-icon-search" size="small" @click="search">查询
            </el-button>
          </el-form>

        </el-row>
        <el-row class="rowSpace">
          <el-col :span="88">
            <el-button @click="handleCreate" size="small" type="primary">创建证书</el-button>

            <!-- 输入页码导出表格 -->
            <el-button type="primary" size="small" @click="dialogFormVisible = true">导出Excel表格</el-button>
            <el-dialog title="请输入导出页码" :visible.sync="dialogFormVisible">
              <el-form :model="form" ref="form">
                <el-form-item label="页码" :label-width="formLabelWidth" prop="pid" :rules="[
                  { required: true, message: '页码不能为空' },
                  { type: 'number', message: '页码必须为数字值' }
                ]">

                  <el-input v-model.number="form.pid" autocomplete="off" style="width: 50%;"></el-input>
                  <el-button type="primary" size="small" style="margin-left: 20px;" @click="Excelall">导出全部数据</el-button>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('form')">确 定</el-button>
              </div>
            </el-dialog>
            <!-- 导入Excel表格 -->
            <el-upload class="upload-demo" action="http://43.143.166.235:8090/import" :on-change="handleFileUpload"
              accept=".xlsx">

              <el-button type="primary" size="small" @click="goExcel">导入Excel表格</el-button>

            </el-upload>
          </el-col>
        </el-row>


      </el-card>
    </div>

    <el-card>
      <div>


        <UploadExcel :onSuccess="success" :isShow="isShow" @getShow="getShow"></UploadExcel>

      </div>


      <el-table :data="list" border style="width: 100%" v-loading="loading" element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-table-column prop="id" label="证书序号" width="150">
        </el-table-column>
        <el-table-column prop="pid" label="证书编号" width="180">
        </el-table-column>
        <el-table-column prop="name" label="证书名字" width="300">
        </el-table-column>
        <el-table-column label="证书添加日期" width="250">

          <template slot-scope="scope">
            <span>{{ moment(scope.row.addTime).format("YYYY-MM-DD hh:mm:ss") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="证书使用日期">
          <template slot-scope="scope">
            <span>{{ moment(scope.row.updateTime).format("YYYY-MM-DD hh:mm:ss") }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="select(scope.row)" icon="el-icon-edit" circle></el-button>
            <el-button size="small" type="success" @click="update(scope.row)" icon="el-icon-check" circle></el-button>
            <el-button size="small" type="danger" @click="deleted(scope.row)" icon="el-icon-delete" circle></el-button>
          </template>
        </el-table-column>


      </el-table>


      <div class="block">
        <el-pagination background layout="prev, pager, next" :page-count="pager.pages" :current-page.sync="pager.page"
          @current-change="currentChange">
        </el-pagination>

      </div>
    </el-card>



  </Layout>
</template>
<script>
// import UploadExcel from "@/components/UploadExcel.vue";
import Layout from "@/components/Layout.vue"
import axios from "axios"
import moment from 'moment'
export default {
  data() {
    return {
      total: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      input3: '',
      dddd: {},
      searchList: [],
      list: [],
      loading: false,
      // isShow: false,
      list2: [],
      pager: {
        limit: 10,
        page: 1,
        pages: 1,

      },
      form: {
        pid: ''

      },


      formLabelWidth: '120px'

    }
  },
  components: {
    Layout,
    // UploadExcel
  },
  methods: {
    moment,
    //导入
    handleFileUpload(event) {
      // console.log(event)
      // const file = event;
      // // 将文件存储在Vue组件的data中
      // this.excelFile = file;

      const file = event.raw;

      this.excelFile = file;
      alert('导入成功!');
    },
    printExcel() {
      // 使用FileReader读取Excel文件的内容
      const reader = new FileReader();

      reader.onload = (event) => {
        const data = new Uint8Array(event.target.result);
        const workbook = XLSX.read(data, { type: "array" });
        const firstSheetName = workbook.SheetNames[0]; // "SheetJS" 取出工作表名称
        const worksheet = workbook.Sheets[firstSheetName]; //取出工作表名称对应的表格数据
        const header = this.getHeaderRow(worksheet); //表头名
        const results = XLSX.utils.sheet_to_json(worksheet); //输出数据，除去表头
        this.excelData.results = results;
        this.excelData.header = header;
        this.onSuccess && this.onSuccess(this.excelData);
        // 处理Excel文件的内容，例如将数据渲染到页面上
        // ...
        // 打印输出Excel文件
        window.print(this.excelData);
        console.log(this.excelData)

      };
      reader.readAsArrayBuffer(this.excelFile);

    },

    //导出全部数据表格

    Excelall() {

      console.log(this.total.total)
      axios({
        url: "http://43.143.166.235:8090/chaxun/home?limit=" + this.total.total
      }).then(res => {
        console.log(res)
        this.list2 = res.data.data.list.list,

          require.ensure([], () => {
            const { export_json_to_excel } = require("../excel/Export2Excel.js");
            const fieldName = ["序号", "标准编号", "标准名称", "发布日期", "实施日期"];
            const filterVal = ["id", "pid", "name", "addTime", "updateTime"];
            const data = this.list2.map(v => filterVal.map(j => v[j]));
            export_json_to_excel(fieldName, data, "广西标准化协会团体标准发布统计表");
            alert('导出成功!');
            this.dialogFormVisible = false
          })
      })
    },

    getShow(isShow) {
      this.isShow = isShow
    },

    //输入页面导出表格

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          axios({
            url: 'http://43.143.166.235:8090/chaxun/home?page=' + this.form.pid
          }).then(res => [


            // moment(res.data.data.list.list.addTime).format('YYYY-MM-DD hh:mm:ss'),
            this.list2 = res.data.data.list.list,


            require.ensure([], () => {
              const { export_json_to_excel } = require("../excel/Export2Excel.js");
              const fieldName = ["序号", "标准编号", "标准名称", "发布日期", "实施日期"];
              const filterVal = ["id", "pid", "name", "addTime", "updateTime"];
              const data = this.list2.map(v => filterVal.map(j => v[j]));


              export_json_to_excel(fieldName, data, "广西标准化协会团体标准发布统计表第" + this.form.pid + "页");
              alert('导出成功!');
              this.dialogFormVisible = false
            })
          ])

        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },










    goExcel() {
      this.isShow = true;
    },
    async success(data) {
      // 数据库的key为英文，我们上传的key为中文，需要一一转化
      const userRelations = {
        序号: "id",
        标准编号: "pid",
        标准名称: "name",
        发布日期: "addTime",
        实施日期: "updateTime ",
      };
      // 将key值一一对应
      const newArr = data.results.map((item) => {
        var userInfo = {};
        Object.keys(item).forEach((key) => {
          userInfo[userRelations[key]] = item[key];
        });
        return userInfo;
      });

      this.dddd = newArr
      console.log(this.dddd)
      //   await importEmployee(newArr); // 调用上传接口
      axios({
        url: "http://43.143.166.235:8090/chaxun/add",
        method: "post",
        data: {
          "id": this.dddd[0].id,
          "pid": this.dddd[0].pid,
          "name": this.dddd[0].name
        }
      }).then(res => {
        console.log(res)

      })

      this.$message("上传文件成功");
      this.isShow = false;
    },













    //导出


    // export2Excel() {
    //   require.ensure([], () => {
    //     const { export_json_to_excel } = require("../excel/Export2Excel.js");
    //     const fieldName = ["序号", "标准编号", "标准名称", "发布日期", "实施日期"];
    //     const filterVal = ["id", "pid", "name", "addTime", "updateTime"];
    //     const data = this.list.map(v => filterVal.map(j => v[j]));
    //     export_json_to_excel(fieldName, data, "广西标准化协会团体标准发布统计表");
    //   });
    // },
    search() {
      axios({
        url: "http://43.143.166.235:8090/chaxun/cart?chaxun=" + this.input3
      }).then(res => {
        console.log(res.data.data)
        this.list = res.data.data.getsearch
        console.log(this.list)
      })

    },
    handleCreate() {
      this.$router.push({
        name: 'booklist-create'
      })
    },
    //创建分类
    update(row) {
      this.$router.push({
        name: "booklist-create"
      })
    },
    //分类详情
    select(row) {
      this.$router.push({
        name: "bookDetail",
        params: {
          cid: row.id
        }
      })
    },
    deleted(row) {


      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        axios({
          url: "http://43.143.166.235:8090/chaxun/deleted?id=" + row.id
        }).then(res => {
          console.log(res)
        })

        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      }).finally(() => {
        setTimeout(() => {
          axios({
            url: "http://43.143.166.235:8090/chaxun/home?page=" + this.pager.page + "&limit=" + this.pager.limit
          }).then(res => {
            console.log(res.data.data.list.list)

            this.list = res.data.data.list.list
            this.pager = {
              page: res.data.data.page,
              pages: res.data.data.pages,
              limit: res.data.data.limit
            }

          })
          this.loading = false
        }, 1500)
      });
      // console.log(row.id)
      // axios({
      //   url:"http://43.143.166.235:8090/chaxun/deleted?id="+this.list.id
      // }).then(res=>{
      //   console.log(res)
      // })
    },
    //列表分页
    currentChange(page) {
      this.pager.page = page
      axios({
        url: "http://43.143.166.235:8090/chaxun/home?page=" + this.pager.page + "&limit=" + this.pager.limit
      }).then(res => {

        this.list = res.data.data.list.list
        this.pager = {
          page: res.data.data.page,
          pages: res.data.data.pages,
          limit: res.data.data.limit
        }
      })
    }
  },
  created() {
    this.loading = true
    // console.log("列表", new Date(), moment().format('YYYY-MM-DD hh:mm:ss'))
    axios({
      url: "http://43.143.166.235:8090/chaxun/home?page=" + this.pager.page + "&limit=" + this.pager.limit
    }).then(res => {
      console.log("所有数据", res)
      this.total = res.data.data
      console.log("全部数据", this.total.total)
      this.list = res.data.data.list.list
      this.pager = {
        page: res.data.data.page,
        pages: res.data.data.pages,
        limit: res.data.data.limit
      }

    }).finally(() => {
      setTimeout(() => {
        this.loading = false
      }, 100)
    })

    //证书列表

  }

}
</script>

<style>
.el-breadcrumb {
  line-height: 20px;
}

.block {
  display: flex;
  background-color: #fff;
  justify-content: center;
  padding: 10px 0;

}

.clearfix {
  display: flex;
  justify-content: space-between;
}

.upload-demo {
  display: inline;
  margin-left: 10px;
}
</style>